import React, { ReactElement } from 'react';
import { Keyboard } from 'react-native';

import { modalOpen, modalClose, toolTipOpen } from '../../util/global';
import navigator from '../../util/navigator';
import PortraitAlert from '../../components/Alert/PortraitAlert';
import { UserApi } from '../../api';
import { setUserInfo } from '../../store/user';

// 返回
export const back = (): void => {
  modalClose();
  navigator.goBack();
};

export const backAlert = (): void => {
  Keyboard.dismiss();
  modalOpen({
    Type: (): React.ReactElement => (
      <PortraitAlert
        title="确认返回吗"
        subTitle="填写内容未保存，返回填写内容将会丢失。"
        sureDesc="确认"
        cancelDesc="取消"
        cancelAction={(): void => {
          modalClose();
        }}
        sureAction={back}
      />
    ),
    needBack: true
  });
};

export const uploadHeadPortrait = async (
  imageBase64: string
): Promise<string> => {
  const res = await UserApi.uploadHeadPortrait({ imageBase64 });
  return new Promise((resolve): void => {
    resolve(res.code === 0 && res.data ? res.data.headPortraitURL : '');
  });
};

export const save = (
  headPortrait: string,
  nickName: string,
  gender: number
): void => {
  UserApi.modifyProfile({
    nickName,
    gender,
    headPortraitURL: headPortrait
  }).then((res): void => {
    if (res.code === 0) {
      toolTipOpen({ desc: '修改个人信息成功' });
      setUserInfo({ nickName });
      back();
    }
  });
};

export const sureSave = (
  headPortrait: string,
  nickName: string,
  gender: number
): void => {
  Keyboard.dismiss();

  if (!nickName) {
    toolTipOpen({ desc: '昵称不能为空' });
    return;
  }

  modalOpen({
    Type: (): React.ReactElement => (
      <PortraitAlert
        title="确认修改个人信息？"
        sureDesc="确认"
        cancelDesc="取消"
        cancelAction={modalClose}
        sureAction={(): void => {
          modalClose();
          save(headPortrait, nickName, gender);
        }}
      />
    ),
    needBack: true
  });
};
